class EventsController < ApplicationController
  layout 'model'
  
  def links
    redirect_to :action=> 'sample'
  end
  
  
  def enroll
    @user = User.find_by_user_name(session[:user_id])
    @event = Event.find(params[:id])
    attendance = Attendance.new
    attendance.attending = "yes"
    attendance.user = @user
    attendance.event = @event
    attendance.save
    render :action => 'show'
  end 
  
  def index
    list
    render :action => 'list'
  end
  
  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update, :enroll ],
  :redirect_to => { :action => :list }
  
  def list
    @event_pages, @events = paginate :events, :per_page => 10, :order => 'date desc'
  end
  
  def show
    @event = Event.find(params[:id])
  end
  
  def new
    @event = Event.new
  end
  
  def create
    @event = Event.new(params[:event])
    if @event.save
      flash[:notice] = 'The event was created and all players where invited by email.'
      invite_no_redirect
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end
  
  def edit
    @event = Event.find(params[:id])
  end
  
  def update
    @event = Event.find(params[:id])
    if @event.update_attributes(params[:event])
      flash[:notice] = 'Event was successfully updated.'
      redirect_to :action => 'show', :id => @event
    else
      render :action => 'edit'
    end
  end
  
  def invite_no_redirect
    # event = Event.find(params[:id])
    players = User.find(:all)
    for player in players
      email = UserMailer.create_invite(player)
      email.set_content_type("text/html")
      UserMailer.deliver(email)
    end
  end  
  
  def invite
    invite_no_redirect
    flash[:notice] = 'All users emailed.'
    redirect_to :action => 'list'
  end  
  
  # Paginate the list of user's attendances to events
  def list_attendance
    # retrieve the current user
    user = User.find_by_user_name(session[:user_id])
    
    # set the variables needed by the paginator
    page = (params[:page] ||= 1).to_i
    items_per_page = 10
    offset = (page - 1) * items_per_page
    
    # get the list of all events the player attendde (via the attendances table, rails do the join for us)
    @attendances = user.events


    # create a Paginator, the second argument has to be the number of ALL items on all pages
    @attendance_pages = Paginator.new(self, @attendances.length, items_per_page, page)
    
    # only make a subset of @items available to the view
    @attendances = @attendances [offset..(offset + items_per_page - 1)]
    
  end
  
  
  def destroy
    Event.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
end
